package com.bw.kotlinim.contract.register

import android.util.Log
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.SaveListener
import com.bw.kotlinim.extention.isValidPassword
import com.bw.kotlinim.extention.isValidUserName
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import kotlinx.android.synthetic.main.activity_register.*
import org.jetbrains.anko.doAsync

class RegisterPresenter(val view:RegisterContract.View) : RegisterContract.Presenter{
    private val TAG = "RegisterPresenter"
    override fun register(username: String, password: String, confirmPassword: String) {
        //双层的正则校验
        if (username.isValidUserName()){
            if (password.isValidPassword()){
                if (password==confirmPassword){
                    //打开进度条
                    view.onStartRegister()
                    //开始注册
                    registerBmob(username,password)
                }else view.onConfirmPasswordError()
            }else view.onPasswordError()
        }else view.onUserNameError()
    }

    private fun registerBmob(username: String, password: String) {

        val bmobUser= BmobUser()
        bmobUser.username = username
        bmobUser.setPassword(password)
        bmobUser.signUp(object : SaveListener<BmobUser>() {
            override fun done(bombuser: BmobUser?, e: BmobException?) {
                if (e == null) {
                    //注册到环信
                    registerEaseMob(username,password)

                } else {
                    //注册失败
                        if (e.errorCode==202){
                            view.onUserExist()
                        }else {
                            Log.d(TAG, "done: " + e.message)
                            view.onRegisterFailed("Bmob注册时便," + e.message)
                        }
                }
            }
        })
    }

    private fun registerEaseMob(username: String, password: String) {
        doAsync {
            try {
                //如果不抛出异常代表注册成功
                EMClient.getInstance().createAccount(username, password)//同步方法
                runOnUIThread { view.onRegisterSuccess() }

            }catch (e:HyphenateException){
                //如果捕获异常代表注册失败
                view.onRegisterFailed("环信注册失败:"+e.message)
            }
        }
    }
}










